<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="用户ID" prop="userId">
        <el-input
          v-model="queryParams.userId"
          placeholder="请输入用户ID"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="课程id" prop="courseId">
        <el-input
          v-model="queryParams.courseId"
          placeholder="请输入课程id"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item label="付款时间" prop="payTime">
        <el-date-picker clearable
          v-model="queryParams.payTime"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择付款时间">
        </el-date-picker>
      </el-form-item>
<!--      <el-form-item label="取消时间" prop="cancelTime">-->
<!--        <el-date-picker clearable-->
<!--          v-model="queryParams.cancelTime"-->
<!--          type="date"-->
<!--          value-format="yyyy-MM-dd"-->
<!--          placeholder="请选择取消时间">-->
<!--        </el-date-picker>-->
<!--      </el-form-item>-->
	  <el-form-item label="订单状态" prop="productName">
	            <el-select v-model="form.banci">
	              <el-option
	                v-for="dict in dict.type.sy_course_order"
	                :key="dict.value"
	                :label="dict.label"
	                :value="dict.value"
	              ></el-option>
	            </el-select>
	   </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>

    </el-form>

      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          @click="handleUpdate"
          v-hasPermi="['order:courseOrders:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          @click="handleDelete"
          v-hasPermi="['order:courseOrders:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['order:courseOrders:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>


    <el-table v-loading="loading" :data="ordersList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="订单编号" align="center" prop="orderId" />
      <el-table-column label="用户ID" align="center" prop="userId" />
      <el-table-column label="订单总价格" align="center" prop="totalAmount" />
      <el-table-column label="实际总价格" align="center" prop="actualAmount" />
      <el-table-column label="支付方式" align="center" prop="payType" :formatter="formatpayType" />
      <el-table-column label="订单备注" align="center" prop="orderRemark" />
      <el-table-column label="订单状态 " align="center" prop="payStatus" :formatter="formatpayStatus" />
      <el-table-column label="付款时间" align="center" prop="payTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.payTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
     <!-- <el-table-column label="发货时间" align="center" prop="deliveryTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.deliveryTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="完成时间" align="center" prop="flishTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.flishTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column> -->
      <el-table-column label="取消时间" align="center" prop="cancelTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.cancelTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['order:courseOrders:edit']"
          >修改</el-button>
		  <el-button
		    size="mini"
		    type="text"
		    icon="el-icon-view"
		    @click="handleView(scope.row)"
		    v-hasPermi="['order:courseOrders:list']"
		  >查看</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['order:courseOrders:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改课程订单对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
		  <el-form-item label="订单编号" prop="orderId">
		    <el-input v-model="form.orderId" placeholder="请输入订单编号" />
		  </el-form-item>
        <el-form-item label="用户ID" prop="userId">
          <el-input v-model="form.userId" placeholder="请输入用户ID" />
        </el-form-item>
        <el-form-item label="课程id" prop="courseId">
          <el-input v-model="form.courseId" placeholder="请输入课程id" />
        </el-form-item>
        <el-form-item label="订单总价格" prop="totalAmount">
          <el-input v-model="form.totalAmount" placeholder="请输入订单总价格" />
        </el-form-item>
        <el-form-item label="实际总价格" prop="actualAmount">
          <el-input v-model="form.actualAmount" placeholder="请输入实际支付总价格" />
        </el-form-item>
        <el-form-item label="订单备注" prop="orderRemark">
          <el-input v-model="form.orderRemark" placeholder="请输入订单备注" />
        </el-form-item>
        <el-form-item label="付款时间" prop="payTime">
          <el-date-picker clearable
            v-model="form.payTime"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择付款时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="发货时间" prop="deliveryTime">
          <el-date-picker clearable
            v-model="form.deliveryTime"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择发货时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="完成时间" prop="flishTime">
          <el-date-picker clearable
            v-model="form.flishTime"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择完成时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="取消时间" prop="cancelTime">
          <el-date-picker clearable
            v-model="form.cancelTime"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择取消时间">
          </el-date-picker>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <el-dialog :title="title" :visible.sync="viewOpen" width="1000px" append-to-body custom-class="view-dialog">
      <el-descriptions class="margin-top" :column="3" :size="size" border>
        <!-- Top Section -->
        <el-descriptions-item label="订单编号">{{ form.orderId }}</el-descriptions-item>
        <el-descriptions-item label="订单总价格">{{ form.totalAmount }}</el-descriptions-item>
        <el-descriptions-item label="实际总价格">{{ form.actualAmount }}</el-descriptions-item>
        <el-descriptions-item label="支付方式"prop="payType" >
			<dict-tag
			:options="dict.type.sy_product_paytype"
			:value="form.payType"
			/>
		</el-descriptions-item>
        <el-descriptions-item label="订单备注">{{ form.orderRemark }}</el-descriptions-item>
        <el-descriptions-item label="付款时间">{{ form.payTime }}</el-descriptions-item>
        <el-descriptions-item label="完成时间">{{ form.flishTime }}</el-descriptions-item>
      </el-descriptions>
      <br />
      <!-- Bottom Section -->
      <el-descriptions class="margin-top" :column="2" :size="size" border>
        <el-descriptions-item label="用户ID">{{ form.userId }}</el-descriptions-item>
        <el-descriptions-item label="用户名称">{{ form.syAppUsers.username }}</el-descriptions-item>
        <el-descriptions-item label="用户邮箱">{{ form.syAppUsers.email }}</el-descriptions-item>
        <el-descriptions-item label="电话号码">{{ form.syAppUsers.phone }}</el-descriptions-item>
      </el-descriptions>
      <br />
      <!-- Bottom Section -->
      <el-descriptions class="margin-top" :column="1" :size="size" border>
        <el-descriptions-item label="课程id">{{ form.courseId }}</el-descriptions-item>
        <el-descriptions-item label="课程名称">{{ form.syCourse.courseName }}</el-descriptions-item>
        <el-descriptions-item label="作者">{{ form.syCourse.username }}</el-descriptions-item>
        <el-descriptions-item label="课程简介">{{ form.syCourse.courseIntro }}</el-descriptions-item>
        <el-descriptions-item label="缩略图">
          <image-preview :src="form.syCourse.thum" :width="200" :height="200"/>
        </el-descriptions-item>
      </el-descriptions>
      <div slot="footer" class="dialog-footer">
        <el-button @click="viewClose">关 闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listOrders, getOrders, delOrders, addOrders, updateOrders,getUserOrders } from "@/api/order/courseOrders.js";


export default {
  name: "Orders",
  dicts: ['sy_course_order','sy_product_paytype'],

  data() {
    return {
      title: "操作",
      open: false,
      size: 'medium',
      viewOpen: false,
      loading: true,
      showSearch: true,
      ordersList: [],
      total: 0,
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        orderId: null,
        userId: null,
        courseId: null,
        totalAmount: null,
        actualAmount: null,
        payType: null,
        orderRemark: null,
        payStatus: null,
        deleteStatus: null,
        payTime: null,
        deliveryTime: null,
        flishTime: null,
        cancelTime: null,
        username: null
      },
      form: {
        orderId: null,
        userId: null,
        courseId: null,
        totalAmount: null,
        actualAmount: null,
        payType: null,
        orderRemark: null,
        payStatus: null,
        deleteStatus: null,
        payTime: null,
        deliveryTime: null,
        flishTime: null,
        cancelTime: null,
        syAppUsers: {
          username: null,
          email: null,
          phone: null,
        },
        syCourse: {
          courseName: null,
          username: null,
          courseIntro: null,
          thum: null,
        },
      },
      rules: {
        userId: [
          { required: true, message: "用户ID不能为空", trigger: "blur" }
        ],
      },
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询课程订单列表 */
    getList() {
      this.loading = true;
      listOrders(this.queryParams).then(response => {
        this.ordersList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
	viewClose(){
	  this.viewOpen = false;
	},
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
   reset() {
     this.form = {
       orderId: null,
       userId: null,
       courseId: null,
       totalAmount: null,
       actualAmount: null,
       payType: null,
       orderRemark: null,
       payStatus: null,
       deleteStatus: null,
       payTime: null,
       deliveryTime: null,
       flishTime: null,
       cancelTime: null,
       syAppUsers: {
         username: null,
         email: null,
         phone: null,
       },
       syCourse: {
         courseName: null,
         username: null,
         courseIntro: null,
         thum: null,
       },
     };
     this.resetForm("form");
   },
	formatpayType(row){
		const statusMap = {
			1: '微信',
			2: '支付宝',
		};
		return statusMap[row.payType] || '未知';
	},
	formatpayStatus(row) {
		const statusMap = {
			1: '待付款',
			2: '已付款',
			3: '已取消',
			4: '支付失败',
			5: '支付成功',
		};
		return statusMap[row.payStatus] || '未知';
	},
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.orderId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    handleView(row){
      console.log(row)

      const oederId = row.orderId
      getUserOrders(oederId).then(response => {
        this.form = response.data;
		console.log(response.data)
        this.title = "查看";
        this.viewOpen = true; // 打开查看对话框
      });
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加课程订单";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const orderId = row.orderId;
      getOrders(orderId).then(response => {
        if (response.code === 200) { // 假设后端成功响应码为200
          this.form = { ...this.form, ...response.data };
          if (!this.form.syAppUsers) {
            this.form.syAppUsers = {
              username: null,
              email: null,
              phone: null,
            };
          }
          if (!this.form.syCourse) {
            this.form.syCourse = {
              courseName: null,
              username: null,
              courseIntro: null,
              thum: null,
            };
          }
          this.open = true;
          this.title = "修改课程订单";
        } else {
          this.$modal.msgError(response.message || "获取订单信息失败");
        }
      }).catch(error => {
        console.error("获取订单信息失败:", error);
        this.$modal.msgError("获取订单信息失败，请稍后再试");
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.orderId != null) {
            updateOrders(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addOrders(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const orderIds = row.orderId || this.ids;
      this.$modal.confirm('是否确认删除课程订单编号为"' + orderIds + '"的数据项？').then(function() {
        return delOrders(orderIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/orders/export', {
        ...this.queryParams
      }, `orders_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
